package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.OrderStatusEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.*;
import com.example.mapper.GoodsMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 康伟奇
 * @date: 2023 - 11 - 13 11:36
 **/
@Service
public class GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private CategoryService categoryService;

    @Resource
    private OrdersItemService ordersItemService;

    @Resource
    private OrdersService ordersService;

    //商家只能查询自己店铺的商品，而不是看到所有的商品
    private void checkIsBusiness(Goods goods){
        Account currentUser = TokenUtils.getCurrentUser();
        String role = currentUser.getRole();
        if (RoleEnum.BUSINESS.name().equals(role)){
            goods.setBusinessId(currentUser.getId());
        }
    }

    //新增
    public void add(Goods goods) {
        //权限校验
        businessService.checkBusinessAuth();
        //查询分类的数据
        Category category = categoryService.selectById(goods.getCategoryId());
        if (ObjectUtil.isNotEmpty(category)){
            goods.setBusinessId(category.getBusinessId());
        }
        goodsMapper.insert(goods);
    }

    //根据id进行删除
    public void deleteById(Integer id) {
        //权限校验
        businessService.checkBusinessAuth();
        goodsMapper.deleteById(id);
    }

    //批量删除
    public void deleteBatch(List<Integer> ids) {
        //权限校验
        businessService.checkBusinessAuth();
        for (Integer id : ids) {
            goodsMapper.deleteById(id);
        }
    }

    //修改
    public void updateById(Goods goods) {
        //权限校验
        businessService.checkBusinessAuth();
        goodsMapper.updateById(goods);
    }

    //根据id查询商品
    public Goods selectById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        wrapGoods(goods);
        return goods;
    }

    //查询所有商品
    public List<Goods> selectAll(Goods goods) {
        checkIsBusiness(goods);
        List<Goods> goodsList = goodsMapper.selectAll(goods);
        for (Goods good : goodsList) {
            wrapGoods(good);
        }
        return goodsList;
    }

    //分页查询
    public PageInfo<Goods> selectPage(Goods goods , Integer pageNum , Integer pageSize) {
        checkIsBusiness(goods);
        PageHelper.startPage(pageNum,pageSize);
        List<Goods> list = goodsMapper.selectAll(goods);
        for (Goods g : list) {
            wrapGoods(g);
        }
        return PageInfo.of(list);
    }

    /**
     * 设置商品的额外信息（实际金额）
     * @param goods
     */
    private void wrapGoods(Goods goods){
        if (goods == null){
            return;
        }

        int saleCount = 0;
        List<OrdersItem> ordersItemList = ordersItemService.selectByGoodsId(goods.getId());
        List<OrdersItem> usageOrderItemList = new ArrayList<>();
        for (OrdersItem ordersItem : ordersItemList) {
            Integer orderId = ordersItem.getOrderId();
            Orders orders = ordersService.selectById(orderId);
            if (orders == null){
                continue;
            }
            if (OrderStatusEnum.NO_COMMENT.getValue().equals(orders.getStatus()) || OrderStatusEnum.DONE.getValue().equals(orders.getStatus())){
                usageOrderItemList.add(ordersItem);
            }
        }
        saleCount += usageOrderItemList.stream().map(OrdersItem::getNum).reduce(Integer::sum).orElse(0);
        goods.setSaleCount(saleCount);

        BigDecimal actualPrice = goods.getPrice().multiply(BigDecimal.valueOf(goods.getDiscount())).setScale(2, RoundingMode.UP);
        goods.setActualPrice(actualPrice);
    }

    public void deleteByBusinessId(Integer businessId) {
        goodsMapper.deleteByBusinessId(businessId);
    }
}
